package cn.diancan.action.api;


import cn.diancan.exception.OutMsgException;
import cn.diancan.model.Goods;
import cn.diancan.model.MealLocation;
import cn.diancan.model.types.CommonConstant;
import cn.diancan.model.types.CommonType;
import cn.diancan.util.DateUtil;
import cn.diancan.util.GoodsCategoryUtils;
import cn.diancan.util.MoneyUtil;
import cn.diancan.util.print.PrintUtil;
import cn.diancan.util.print.ProductPrint;
import cn.diancan.util.print.ProductTableVo;
import cn.diancan.vo.PurchaseSaleOrderCountVo;
import cn.diancan.vo.SaleOrderCarVo;
import cn.diancan.vo.SaleProductCarVo;
import com.alibaba.fastjson.JSONObject;
import com.opensymphony.xwork2.ModelDriven;

import cn.diancan.action.BaseAction;
import cn.diancan.model.PurchaseSaleOrder;
import cn.diancan.util.spring.AllThreadPool;
import cn.diancan.util.spring.NotifyThread;
import cn.diancan.vo.mobile.PurchaseSaleOrderApiActionVo;
import cn.diancan.vo.model.PurchaseSaleOrderVo;
import cn.diancan.vo.model.SaleOrderVo;

import java.util.*;

public class PurchaseSaleOrderAction extends BaseAction implements ModelDriven<PurchaseSaleOrderApiActionVo> {

    private PurchaseSaleOrderApiActionVo requestVo = new PurchaseSaleOrderApiActionVo();

    public String uploadSaleOrder() {
        /*JSONObject jo = JSONObject.parseObject(json);
        jo.get("purchaseSaleOrder");
        jo.getJSONArray("purchaseSaleOrderProductList");*/

        try {
            String json = requestVo.getJson();
            SaleOrderVo saleOrderVo = JSONObject.parseObject(json, SaleOrderVo.class);
            PurchaseSaleOrderVo vo = saleOrderVo.getPurchaseSaleOrder();

            PurchaseSaleOrder saleOrder = purchaseSaleOrderService.saveCreateSaleOrder(saleOrderVo.getPurchaseSaleOrderProductList(),
                    vo.getOutOrderNumber(), vo.getOutRealTotalQuantity(), vo.getOutRealTotalPrice(),
                    vo.getOrderMark(), vo.getMoneyFloatDigit(), vo.getClientCreateTime(), vo.getShopClerkId(), vo.getPayType(), getIpAddr());

            try {
                AllThreadPool.NotifyThreadPool.execute(new NotifyThread(saleOrder.getOutOrderNumber(), getBasePath()));
            } catch (Exception e) {
                e.printStackTrace();
            }
            return jsonFormat(null != saleOrder);
        } catch (Exception e) {
            return jsonError(e);
        }
    }


    public String singleSaleOrder() {
        try {
            SaleOrderCarVo singlePurchaseSaleOrder = purchaseSaleOrderService.findSinglePurchaseSaleOrder(requestVo.getOutOrderNumber(), true);
            return jsonFormat(singlePurchaseSaleOrder);
        } catch (Exception e) {
            return jsonError(e);
        }
    }


    /**
     * 上传
     * @return
     */
    public String uploadSaleOrderProduct(){
        try {
            SaleProductCarVo productCarVo = requestVo.vo2ProductCarVo();
            PurchaseSaleOrderVo purchaseSaleOrderVo = requestVo.vo2PurchaseSaleOrderVo();
            SaleOrderCarVo saleOrderCarVo = purchaseSaleOrderService.updatePurchaseSaleProduct(purchaseSaleOrderVo, productCarVo);
            return jsonFormat(saleOrderCarVo);
        } catch (Exception e) {
            return jsonError(e);
        }
    }


    /**
     * 取消订单
     * @return
     */
    public String cancelOrder(){
        try {
            boolean b = purchaseSaleOrderService.updateCancelOrder(requestVo.getOutOrderNumber());
            return jsonFormat(b,"取消成功","取消失败");
        } catch (Exception e) {
            return jsonError(e);
        }
    }


    /**
     * 移动
     * @return
     */
    public String moveMealLoactionOrder(){
        try {
            boolean b = purchaseSaleOrderService.updateMoveMealLoaction(requestVo.getOutOrderNumber(), requestVo.getMealLocationId());
            return jsonFormat(b,"操作成功","操作失败");
        } catch (Exception e) {
            return jsonError(e);
        }
    }

    /**
     * 优惠买单
     * @return
     */
    public String discountOrder(){
        try {
            SaleOrderCarVo saleOrderCarVo = purchaseSaleOrderService.updateDiscount(requestVo.getOutOrderNumber(), requestVo.getDiscountType(), requestVo.getDiscount(), requestVo.getDiscountPrice());
            return jsonFormat(saleOrderCarVo,"修改成功","修改失败");
        } catch (Exception e) {
            return jsonError(e);
        }
    }


    /**
     * 付款
     * @return
     */
    public String payOrder(){
        try {
            boolean b = purchaseSaleOrderService.updatePayOrder(requestVo.getOutOrderNumber(), requestVo.getPayType());
            return jsonFormat(b,"付款成功","付款失败");
        } catch (Exception e) {
            return jsonError(e);
        }
    }

    /**
     * 打印全部
     * @return
     */
    public String printOrder(){

        return pritnOrder(requestVo.getOutOrderNumber(), null,true);
    }

    /**
     * 部分打印
     * @return
     */
    public String partPrintOrder(){
        try {
            String[] purchaseSaleOrderProducts =  requestVo.getPurchaseSaleOrderProducts().split(",");


            Map<Long,Integer> purchaseSaleOrderProductMap = new HashMap<Long,Integer>();



            for (int i=0;i<purchaseSaleOrderProducts.length; i++){
                try {
                    String[] split = purchaseSaleOrderProducts[i].split("\\|");
                    purchaseSaleOrderProductMap.put(Long.valueOf(split[0]),Integer.valueOf(split[1])) ;
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            return pritnOrder(requestVo.getOutOrderNumber(),purchaseSaleOrderProductMap,false);
        } catch (Exception e) {
            return jsonError(e);
        }
    }


    private String pritnOrder(String outOrderNumber,Map<Long,Integer> purchaseSaleOrderProductMap,boolean isAll){
        try {
            SaleOrderCarVo singlePurchaseSaleOrder = purchaseSaleOrderService.findSinglePurchaseSaleOrder(outOrderNumber,false );
            List<ProductTableVo> productTableVos = new ArrayList<ProductTableVo>();
            List<ProductTableVo> productTableVos2 = new ArrayList<ProductTableVo>();
            List<ProductTableVo> productTableVos3 = new ArrayList<ProductTableVo>();
            List<ProductTableVo> productTableVos4 = new ArrayList<ProductTableVo>();
            GoodsCategoryUtils.load();

            List<SaleProductCarVo> saleProductCars = singlePurchaseSaleOrder.getSaleProductCars();
            if(null == saleProductCars ){
                throw new OutMsgException("参数错误");
            }


            Double realTotalPrice = singlePurchaseSaleOrder.getRealTotalPrice();
            Double discountPrice = singlePurchaseSaleOrder.getDiscountPrice();
            Float discount = singlePurchaseSaleOrder.getDiscount();
            Double realRetailPrice = singlePurchaseSaleOrder.getRealRetailPrice();
            Integer totalQuantity = singlePurchaseSaleOrder.getTotalQuantity();

            if(!isAll  ){
                realTotalPrice = 0d;
                discountPrice = 0d;
                discount = 1f;
                realRetailPrice = 0d;
                totalQuantity = 0;
            }

            for (SaleProductCarVo saleProductCarVo: saleProductCars){

                ProductTableVo productTableVo = new ProductTableVo();
                productTableVo.setGoodsName(saleProductCarVo.getGoodsName());
                productTableVo.setUnit(saleProductCarVo.getUnit());
                productTableVo.setRetailPrice(saleProductCarVo.getRetailPrice());
                productTableVo.setDiscount(1F);//不显示

                boolean isAdd =false;

                if(isAll  ){
                    productTableVo.setQuantity(saleProductCarVo.getQuantity());
                    productTableVo.setTurnover(saleProductCarVo.getRealTotalPrice());

                    isAdd =true;

                   /* if(saleProductCarVo.getIsCanDiscount().equals(CommonType.Discount.YES)){
                        productTableVos.add(productTableVo);
                    }else {
                        productTableVos2.add(productTableVo);
                    }*/
                }else if( purchaseSaleOrderProductMap != null &&  purchaseSaleOrderProductMap.containsKey(saleProductCarVo.getPurchaseSaleOrderProductId()) ){

                    productTableVo.setQuantity(purchaseSaleOrderProductMap.get(saleProductCarVo.getPurchaseSaleOrderProductId()));
                    productTableVo.setTurnover(MoneyUtil.mul(productTableVo.getQuantity(),saleProductCarVo.getRetailPrice()));

                    realTotalPrice = MoneyUtil.add(productTableVo.getTurnover(), realTotalPrice) ;
                    realRetailPrice =MoneyUtil.add(productTableVo.getTurnover(), realRetailPrice) ;
                    totalQuantity += productTableVo.getQuantity();

                    isAdd =true;
                   /* if(saleProductCarVo.getIsCanDiscount().equals(CommonType.Discount.YES)){
                        productTableVos.add(productTableVo);
                    }else {
                        productTableVos2.add(productTableVo);
                    }*/

                }

                if(isAdd){
                    if(saleProductCarVo.getGoodsCategoryId().equals(GoodsCategoryUtils.canju)){
                        productTableVos4.add(productTableVo);
                    }else if(saleProductCarVo.getGoodsCategoryId().equals(GoodsCategoryUtils.jiushui)){
                        productTableVos3.add(productTableVo);
                    }else  if(saleProductCarVo.getGoodsCategoryId().equals(GoodsCategoryUtils.lengpan)){
                        productTableVos2.add(productTableVo);
                    }else {
                        productTableVos.add(productTableVo);
                    }
                }




            }

            MealLocation mealLocation = mealLocationService.findbyMealLocationId(singlePurchaseSaleOrder.getMealLocationId());

            if(productTableVos.size()<=0 && productTableVos2.size()<=0 && productTableVos3.size()<=0 && productTableVos4.size()<=0){
                return jsonFormat(false,"打印成功","打印失败");
            }
            if(null==mealLocation){
                throw new OutMsgException("座位参数错误");
            }

            ProductPrint pro = new ProductPrint(  singlePurchaseSaleOrder.getOutOrderNumber(),
                    DateUtil.currentDateTime(),"巧鱼馆", "巧鱼馆","八仙楼巧鱼馆" ,"0001", "温州市鹿城区八仙楼", "---",
                    realTotalPrice, discountPrice, discount, realRetailPrice, 0, 0d, totalQuantity);

            pro.init2(mealLocation.getLocationType(),mealLocation.getLocationName(),singlePurchaseSaleOrder.getCustomerName(),singlePurchaseSaleOrder.getCustomerPhone(),
                    singlePurchaseSaleOrder.getCustomerAddress(),singlePurchaseSaleOrder.getCustomerRemark());

            pro.init3(productTableVos,productTableVos2,productTableVos3,productTableVos4);


            PrintUtil.print(pro);

            return jsonFormat(true,"打印成功","打印失败");
        } catch (Exception e) {
            return jsonError(e);
        }
    }


    public String outSendOrderList(){
        try {
            List<PurchaseSaleOrder> purchaseSaleOrders = purchaseSaleOrderService.findOutSendOrderList(requestVo.getMealLocationId() );
            return jsonFormat(purchaseSaleOrders);
        } catch (Exception e) {
            return jsonError(e);
        }
    }

    //首页统计
    public String indexOrderCount(){
        try {
            PurchaseSaleOrderCountVo count = purchaseSaleOrderService.findCount();
            return jsonFormat(count);
        } catch (Exception e) {
            return jsonError(e);
        }
    }


    public String outMealOrderCount(){
        try {
            PurchaseSaleOrderCountVo outMealCount = purchaseSaleOrderService.findOutMealCount(requestVo.getMealLocationId());
            return jsonFormat(outMealCount);
        } catch (Exception e) {
            return jsonError(e);
        }
    }

/*    public String t1(){
        try {
            Goods goods  = new Goods();
            goods.setBrandId(CommonConstant.brandId);
            goods.setGoodsCategoryId(CommonConstant.HideGoodsCategoryId);
            String newGoodsNumber = goodsService.findNewGoodsNumber();
            goods.setGoodsNumber(newGoodsNumber);
            goods.setGoodsName("小菜"+newGoodsNumber);
            goods.setGoodsDescription("");
            goods.setGoodsBarCode("");


            goods.setRangeStr("");
            goods.setTagPrice(Double.valueOf(0)); // 吊牌价
            goods.setRetailPrice(Double.valueOf(0)); // 销售价格
            goods.setUnit("份");

            goods.setYear("2017"); // 年份
            goods.setSeason("春夏"); // 季节
            goods.setApplySex(2); // 0 女 1 男 2 全部
            goods.setWholeSalePrice(Double.valueOf(0));//
            goods.setGoodsRemark("");


            Goods goods2 = goodsService.saveGoods2(goods, true);
            return jsonFormat(null == goods2);
        } catch (Exception e) {
            return jsonError(e);
        }

    }*/

    @Override
    public PurchaseSaleOrderApiActionVo getModel() {
        return requestVo;
    }



}
